//全局函数封装
var GloabFun = (function(mod, document) {
	var loopOpreation = null;
	var Cookie = {};

	Cookie.write = function(name, value, day = 0) {
		if(day !== 0) { //当设置的时间等于0时，不设置expires属性，cookie在浏览器关闭后删除
			var expires = day * 24 * 60 * 60 * 1000;
			var date = new Date(+new Date() + expires);
			document.cookie = name + "=" + escape(value) + ";expires=" + date.toUTCString();
		} else {
			document.cookie = name + "=" + escape(value);
		}
	};

	Cookie.read = function(name) {
		var arr;
		var reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
		if(arr = document.cookie.match(reg)) {
			return unescape(arr[2]);
		} else {
			return null;
		}
	};

	var getValue = (key) => {
		if(Cookie.read(key)){
			return Cookie.read(key)
		}else if(localStorage.getItem(key)){
			return localStorage.getItem(key)
		}else{
			return ""
		}
	}

	mod.setCookie = (key, value) => {
		Cookie.write(key, value);
	}

	mod.getCookie = (key) => {
		return Cookie.read(key)
	}
	//token
	mod.getToken = function() {
		return getValue("token");
	}
	mod.setToken = function(token) {
		if(window.localStorage) {
			localStorage.setItem("token", token);
		} else {
			Cookie.write("token", token);
		}
	}
	//uid
	mod.getUid = function() {
		return getValue("uid");
	}

	mod.setUid = function(uid) {
		if(window.localStorage) {
			localStorage.setItem("uid", uid);
		} else {
			Cookie.write("uid", uid);
		}
	}
	//keyid
	mod.getKeyId = function() {
		return getValue("keyid");
	}

	mod.setKeyId = function(key) {
		if(window.localStorage) {
			localStorage.setItem("keyid", key);
		} else {
			Cookie.write("keyid", key);
		}
	}
	//保存书籍搜索历史
	//search
	mod.getSearchBook = function() {
		return window.localStorage ? localStorage.getItem("searchBook") ? localStorage.getItem("searchBook") : "" : Cookie.read("searchBook") ? Cookie.read("searchBook") : "";
	}

	mod.setSearchBook = function(search) {
		if(window.localStorage) {
			localStorage.setItem("searchBook", search);
		} else {
			Cookie.write("searchBook", search);
		}
	}
	//保存读者搜索历史
	//searchReader
	mod.getSearchReader = function() {
		return window.localStorage ? localStorage.getItem("searchReader") ? localStorage.getItem("searchReader") : "" : Cookie.read("searchReader") ? Cookie.read("searchReader") : "";
	}

	mod.setSearchReader = function(searchReader) {
		if(window.localStorage) {
			localStorage.setItem("searchReader", searchReader);
		} else {
			Cookie.write("searchReader", searchReader);
		}
	}

	//nickname
	mod.getNickName = function() {
		return getValue("nickname");
	}

	mod.setNickName = function(nickname) {
		if(window.localStorage) {
			localStorage.setItem("nickname", nickname);
		} else {
			Cookie.write("nickname", nickname);
		}
	}

	//读者--code
	mod.getReaderCode = function() {
		return window.localStorage ? localStorage.getItem("readerCode") ? localStorage.getItem("readerCode") : "" : Cookie.read("readerCode") ? Cookie.read("readerCode") : "";
	}

	mod.setReaderCode = function(readerCode) {
		if(window.localStorage) {
			localStorage.setItem("readerCode", readerCode);
		} else {
			Cookie.write("readerCode", readerCode);
		}
	}
	//读者--name
	mod.getReaderName = function() {
		return window.localStorage ? localStorage.getItem("readerName") ? localStorage.getItem("readerName") : "" : Cookie.read("readerName") ? Cookie.read("readerName") : "";
	}

	mod.setReaderName = function(readerName) {
		if(window.localStorage) {
			localStorage.setItem("readerName", readerName);
		} else {
			Cookie.write("readerName", readerName);
		}
	}
	//读者--role
	mod.getReaderRole = function() {
		return window.localStorage ? localStorage.getItem("readerRole") ? localStorage.getItem("readerRole") : "" : Cookie.read("readerRole") ? Cookie.read("readerRole") : "";
	}

	mod.setReaderRole = function(readerRole) {
		if(window.localStorage) {
			localStorage.setItem("readerRole", readerRole);
		} else {
			Cookie.write("readerRole", readerRole);
		}
	}
	//读者--keyid
	mod.getReaderKeyid = function() {
		return window.localStorage ? localStorage.getItem("readerKeyid") ? localStorage.getItem("readerKeyid") : "" : Cookie.read("readerKeyid") ? Cookie.read("readerKeyid") : "";
	}

	mod.setReaderKeyid = function(readerKeyid) {
		if(window.localStorage) {
			localStorage.setItem("readerKeyid", readerKeyid);
		} else {
			Cookie.write("readerKeyid", readerKeyid);
		}
	}
	//清除读者登录信息
	mod.clearReaderLoginInfo = function(token) {
		if(window.localStorage) {
			localStorage.setItem("readerCode", "");
			localStorage.setItem("readerKeyid", "");
			localStorage.setItem("readerName", "");
			localStorage.setItem("readerRole", "");
		} else {
			Cookie.write("readerCode", "");
			Cookie.write("readerKeyid", "");
			Cookie.write("readerName", "");
			Cookie.write("readerRole", "");
		}
	}
	//清除信息
	mod.clearLoginInfo = function(token) {
		if(window.localStorage) {
			localStorage.clear(); //清除所有
		} else {
			Cookie.write("nickname", "");
			Cookie.write("uid", "");
			Cookie.write("token", "");
			Cookie.write("keyid", "");
			Cookie.write("searchBook", "");
			Cookie.write("searchReader", "");
		}
	}

	mod.trim = function(str) { //删除左右两端的空格
		　　
		return str.replace(/(^\s*)|(\s*$)/g, "");　　
	}
	mod.getLoopOpreation = function() {
		return loopOpreation;
	};
	mod.setLoopOpreation = function(fn) {
		if(fn === null) {
			loopOpreation = null;
		} else {
			loopOpreation = setInterval(function() {
				this.$http.post(localHost + '/rest/v1/Login/Online', {}, {
					headers: {
						"access_token": mod.getToken()
					}
				}).then(function(response) {
					//console.log(response);
				}, function(response) {
					clearInterval(loopOpreation);
					loopOpreation = null;
					// console.error(this.$t('message.error'));
					//this.$alert(this.$t('message.requestError'), this.$t('message.error'),{type:"error"});
				});
			}.bind(this), 60000);
		}
	}

	mod.clearRecordPreview = function() {
		try {
			if(recordGId) {
				//清除开启的录播预览
				this.$http.post(localHost + '/rest/v1/record/PreviewClose/' + recordGId, {}, {
					headers: {
						"access_token": mod.getToken()
					}
				}).then(function(response) {
					recordGId = "";
				});
			}
		} catch(e) {}
	}

	//后台统一文件下载处理
	mod.downLoadFile = (fileName, fileType, responseData) => {
		const blob = new Blob([responseData], { type: '' })
		const link = document.createElement('a')
		document.body.appendChild(link)
		link.href = window.URL.createObjectURL(blob)
		link.download = `${fileName}.${fileType}`
		link.click()
		document.body.removeChild(link)
	}

	return mod;
}(window.GloabFun || {}, document));

//切换动画效果
var Animation = (function(mod, document) {
	mod.animation = function($obj, fn) {
		$obj.fadeOut(500, function() {
			fn();
			$obj.fadeIn(500)
		});
	}
	mod.cssChange = function($obj, styles, fn) {
		$obj.animate(styles, {
			speed: 500,
			callback: fn
		});
	}
	return mod;
}(window.Animation || {}, document));

//Http封装
var HttpServer = (function(mod, document, gloabFun) {
	var successResponse = function(response, callback, error) {
			if(response.status && response.status === 200) {
				if(response.data.code === 10022) {
					if(document.getElementsByClassName('el-message-box').length === 0) {
						GloabFun.clearLoginInfo();
						this.$alert(this.$t('message.userUnLogin'), this.$t('message.warning'), {
							callback: action => {
								this.$router.push({
									path: '/Login'
								});
							},
							type: "warning"
						});
					}
				} else if(response.data.code === 10023 || response.data.code === 10031) {
					if(document.getElementsByClassName('el-message-box').length === 0) {
						GloabFun.clearLoginInfo();
						this.$alert(this.$t('登录已失效，请重新登录'), this.$t('message.warning'), {
							callback: action => {
								this.$router.push({
									path: '/Login'
								});
							},
							type: "warning"
						});
					}
				} else {
					if(error) {
						error.call(this, response);
					} else {
						// this.$alert(response.data.msg, this.$t('message.error'),{type:"error"});
					}
				}
			} else {
				// this.$message({
				// 	type:'error',
				// 	message:'操作失败，错误码：' + response.status
				// });
			}
		},
		errorResponse = function() {
			// this.$alert(this.$t('message.requestError'), this.$t('message.error'),{type:"error"});
		};

	//在用方法
	mod.httpGet = function(url, callback, error) {
		this.$http.get(localHost + url, {
			headers: {
				"token": GloabFun.getToken()
			}
		}).then(function(response) {
			successResponse.call(this, response, callback, error);
		}.bind(this), function(response) {
			errorResponse.call(this, error);
		}.bind(this));
	}

	mod.httpGet2 = function(url, callback, error) {
		var access_token_str = "";
		if(url.indexOf("?") === -1) {
			access_token_str = `?Token='${GloabFun.getToken()}&UserLoginName=${GloabFun.getUid()}&UserKeyId=${GloabFun.getKeyId()}`;
		} else {
			access_token_str = `&Token='${GloabFun.getToken()}&UserLoginName=${GloabFun.getUid()}&UserKeyId=${GloabFun.getKeyId()}`;
		}
		this.$http.get(localHost + url + access_token_str, {
			headers: {
				"token": GloabFun.getToken()
			}
		}).then(function(response) {
			successResponse.call(this, response, callback, error);
		}.bind(this), function(response) {
			errorResponse.call(this, error);
		}.bind(this));
	}
	//需要用到uid和token的post操作   在用方法
	mod.httpPost = function(url, data, callback, error) {
		data.uid = GloabFun.getUid();
		data.token = GloabFun.getToken();
		this.$http.post(localHost + url, data).then(function(response) {
			successResponse.call(this, response, callback, error);
		}.bind(this), function(response) {
			errorResponse.call(this, error);
		}.bind(this));
	}
	//入参不需要uid和token  在用方法
	mod.httpPost2 = function(url, data, callback, error) {
		this.$http.post(localHost + url, data).then(function(response) {
			successResponse.call(this, response, callback, error);
		}.bind(this), function(response) {
			errorResponse.call(this, error);
		}.bind(this));
	}
	// mod.httpPut = function(url, data, callback,error) {
	// 	data.uid = GloabFun.getUid();
	// 	data.token = GloabFun.getToken();
	// 	this.$http.put(localHost+url, data).then(function(response) {
	// 		successResponse.call(this, response, callback,error);
	// 	}.bind(this), function(response) {
	// 		errorResponse.call(this,error);
	// 	}.bind(this));
	// }

	// mod.httpPost2 = function(url, data, callback,error) {
	// 	var access_token_str="";
	//    	if(url.indexOf("?")===-1){
	//           access_token_str='?access_token='+GloabFun.getToken();
	//    	}else{
	//    		access_token_str='&access_token='+GloabFun.getToken();
	//    	}
	// 	this.$http.post(localHost+url+access_token_str, data, {
	// 		headers: {
	// 			"access_token": GloabFun.getToken()
	// 		}
	// 	}).then(function(response) {
	// 		successResponse.call(this, response, callback,error);
	// 	}.bind(this), function(response) {
	// 		errorResponse.call(this,error);
	// 	}.bind(this));
	// }

	//    mod.httpPut2 = function(url, data, callback,error) {
	//    	var access_token_str="";
	//    	if(url.indexOf("?")===-1){
	//           access_token_str='?access_token='+GloabFun.getToken();
	//    	}else{
	//    		access_token_str='&access_token='+GloabFun.getToken();
	//    	}
	// 	this.$http.put(localHost+url+access_token_str, data, {
	// 		headers: {
	// 			"access_token": GloabFun.getToken()
	// 		}
	// 	}).then(function(response) {
	// 		successResponse.call(this, response, callback,error);
	// 	}.bind(this), function(response) {
	// 		errorResponse.call(this,error);
	// 	}.bind(this));
	// }

	// mod.httpDelete = function(url, callback,error) {
	// 	this.$http.delete(localHost+url, {
	// 		headers: {
	// 			"access_token": GloabFun.getToken()
	// 		}
	// 	}).then(function(response) {
	// 		successResponse.call(this, response, callback,error);
	// 	}.bind(this), function(response) {
	// 		errorResponse.call(this,error);
	// 	}.bind(this));
	// }

	//    mod.httpDelete2 = function(url, callback,error) {
	//    	var access_token_str="";
	//    	if(url.indexOf("?")===-1){
	//           access_token_str='?access_token='+GloabFun.getToken();
	//    	}else{
	//    		access_token_str='&access_token='+GloabFun.getToken();
	//    	}
	// 	this.$http.delete(localHost+url+access_token_str, {
	// 		headers: {
	// 			"access_token": GloabFun.getToken()
	// 		}
	// 	}).then(function(response) {
	// 		successResponse.call(this, response, callback,error);
	// 	}.bind(this), function(response) {
	// 		errorResponse.call(this,error);
	// 	}.bind(this));
	// }
	return mod;
}(window.HttpServer || {}, document, window.GloabFun));

export {
	GloabFun,
	Animation,
	HttpServer
}